package com.spic.business.supervision.service.impl;

import com.spic.business.common.core.workflow.IWorkFlowType;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.common.workflow.WorkFlowServiceImpl;
import com.spic.business.enumconst.BusinessType;
import com.spic.business.supervision.domain.DocSupervision;
import com.spic.business.supervision.mapper.DocSupervisionMapper;
import com.spic.business.supervision.service.IDocSupervisionService;
import com.spic.business.utils.SendSms;
import com.spic.common.core.constant.SecurityConstants;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.system.api.RemoteActivitiTaskService;
import com.spic.system.api.RemoteDeptService;
import com.spic.system.api.RemoteJobService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysJobDto;
import com.spic.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公文督办
 */
@Service
public class DocSupervisionServiceImpl extends WorkFlowServiceImpl<DocSupervisionMapper, DocSupervision> implements IDocSupervisionService
{

    @Autowired
    private DocSupervisionMapper docSupervisionMapper;

    @Autowired
    private RemoteJobService remoteJobService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private RemoteActivitiTaskService remoteActivitiTaskService;


    @Override
    @BusinessDataScope(menuPath = "business/docSupervision/index")
    public List<DocSupervision> selectDocSupervisionList(DocSupervision docSupervision)
    {
        List<DocSupervision> list = docSupervisionMapper.selectDocSupervisionList(docSupervision);
        if (StringUtils.isNotNull(list) && list.size() > 0)
        {
            processRow(list, this::row);
        }
        return list;
    }

    //处理每条业务自己逻辑d
    private void row(DocSupervision ocSupervision)
    {
    }

    @Override
    public DocSupervision selectDocSupervisionById(Integer id)
    {
        return docSupervisionMapper.selectDocSupervisionById(id);
    }

    @Override
    public Long insertDocSupervision(DocSupervision docSupervision)
    {
        docSupervision.setCreateTime(DateUtils.getNowDate());
        docSupervisionMapper.insertDocSupervision(docSupervision);
        //先创建定时任务
        String taskId = this.createJob(docSupervision);
        docSupervision.setTaskId(taskId);
        //更新taskId
        docSupervisionMapper.updateDocSupervision(docSupervision);
        return docSupervision.getId();
    }

    @Override
    public int updateDocSupervision(DocSupervision docSupervision)
    {
        docSupervision.setUpdateTime(DateUtils.getNowDate());
        return docSupervisionMapper.updateDocSupervision(docSupervision);
    }

    @Override
    public int deleteDocSupervisionByIds(Integer[] ids)
    {
        return docSupervisionMapper.deleteDocSupervisionByIds(ids);
    }

    @Override
    protected IWorkFlowType getWorkFlowType()
    {
        return BusinessType.DOC_SUPERVISION;
    }

    @Override
    protected void setWorkFlowVariable(DocSupervision entity, Map<String, Object> variable)
    {
        String deptIds = entity.getDeptList();
//        List<Long> list = remoteDeptService.getDeptLeaderIdDeptIds(deptIds).getData();
        String[] split = deptIds.split(",");
        Long[] ints = new Long[split.length];
        for(int i=0;i<split.length;i++){
            ints[i] = Long.parseLong(split[i]);
        }
        List<SysUser> data = remoteUserService.getSysUserByDeptIds(ints).getData();
        List<Long> list = data.stream().map(SysUser::getUserId).collect(Collectors.toList());
        variable.put("leaderList", list);
    }

    /**
     * 创建定时任务
     *
     * @param docSupervision
     * @return jobId
     */
    public String createJob(DocSupervision docSupervision)
    {
        SysJobDto job = new SysJobDto();
        job.setJobName("定时发送公文督办短信数据id=" + docSupervision.getId());
        job.setJobGroup("DEFAULT");
        job.setInvokeTarget("sendMsgTask.docSendMsg('" + docSupervision.getId() + "')");
        job.setCronExpression("0 0 0 1/"+docSupervision.getMessageRate()+" * ?");
//        job.setCronExpression("0/20 * * * * ?");
        job.setConcurrent("1");
        job.setStatus("0");
        return remoteJobService.addSysJob(job, SecurityConstants.INNER).getMsg();
    }

    /**
     * 发送短信
     *
     * @param id 数据id
     */
    @Override
    public void sendMsg(String id)
    {
        try
        {
            DocSupervision docSupervision = docSupervisionMapper.selectDocSupervisionById(Integer.valueOf(id));
            if (StringUtils.isEmpty(docSupervision.getInstanceId()))
            {
                return;
            }
            AjaxResult mulitInstanceTask = remoteActivitiTaskService.getMulitInstanceTask(docSupervision.getInstanceId(),"deptDeal");
            List<String> listTask = (List<String>) mulitInstanceTask.get("data");

            if (listTask != null && listTask.size() > 0)
            {
                String deptIds = docSupervision.getDeptList();
//                List<Long> listUserId = remoteDeptService.getDeptLeaderIdDeptIds(deptIds).getData();
                String[] split = deptIds.split(",");
                Long[] ints = new Long[split.length];
                for(int i=0;i<split.length;i++){
                    ints[i] = Long.parseLong(split[i]);
                }
                List<SysUser> data = remoteUserService.getSysUserByDeptIds(ints).getData();
                List<Long> listUserId = data.stream().map(SysUser::getUserId).collect(Collectors.toList());

                String userIds = listTask.stream().collect(Collectors.joining(","));

                //查询未办理的人员电话号码
                List<String> list = new ArrayList<>();
                for (Long userId : listUserId)
                {
                    if (userIds.indexOf(userId + "") != -1)
                    {
                        SysUser sysUser = remoteUserService.getUserById(userId).getData();
                        list.add(sysUser.getPhonenumber());
                    }
                }
                if (list.size() > 0)
                {
                    String receiver = "";
                    for (String phone : list)
                    {
                        receiver += "+86" + phone + ",";
                    }
                    if (receiver.endsWith(","))
                    {
                        receiver = receiver.substring(0, receiver.length() - 1);
                    }
                    String date = DateUtils.getDateTimeBefore("-" + docSupervision.getMessageRate());
                    //模板内容：关于${TASK_TITLE}问题，${DATE_LIMIT}完成,现对你进行督办，下次督办时间为${DATE}，请及时办理。

//                String content = "关于"+docSupervision.getTaskTitle()+"问题，"+docSupervision.getDateLimit()+"完成，" +
//                        "现对你进行督办，下次督办时间为"+date+"。";
                    String content = "[\"" + docSupervision.getTaskTitle() + "\",\"" + docSupervision.getDateLimit() + "\",\"" + date + "\"]";
                    SendSms.sendMsg(receiver, content);//TODO: 调用华为短信服务，发送短信，模板/签名还未创建
                } else
                {
                    Long[] l = new Long[1];
                    l[0] = Long.valueOf(docSupervision.getTaskId());
                    remoteJobService.removeSysJob(l, SecurityConstants.INNER);
                }
            } else
            {
                //删除定时任务
                Long[] l = new Long[1];
                l[0] = Long.valueOf(docSupervision.getTaskId());
                remoteJobService.removeSysJob(l, SecurityConstants.INNER);
                return;
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
